package com.huanglejing.shanggou.presenterimpl


import com.google.gson.JsonObject
import com.huanglejing.shanggou.interfaces.LoginContract.LoginPresenter
import com.huanglejing.shanggou.interfaces.LoginContract.LoginView
import com.huanglejing.shanggou.rx.SchedulersCompat
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.addTo
import com.huanglejing.shanggou.utils.cacheLoginInfo


class LoginPresenterImpl : BasePresenterImpl<LoginView>(), LoginPresenter<LoginView> {
    private val model by lazy { BaseCacheRequestImpl.getInstance(C.APIV1.LOGIN) }
    override fun onFirstLoad() {
        super.onFirstLoad()
        //获取配置信息

    }

    override fun login() {
        mView?.getRequestParams()?.flatMap {
            model?.requestForGet(it)
        }?.compose(SchedulersCompat.io())
                ?.subscribe(object : SimpleSubscriber<JsonObject>() {
                    override fun onStart() {
                        super.onStart()
                        mView?.showLoading()
                    }
                    override fun onNext(t: JsonObject) {
                        super.onNext(t)
                        mView?.dismissLoading()
                        mView?.showContent(t)
                        cacheLoginInfo(t?.getAsJsonObject("data")?.get("name")?.asString
                                ?: "", t?.getAsJsonObject("data")?.get("id")?.asString ?: "")
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        mView?.dismissLoading()
                        mView?.showError(e)
                    }

                })?.addTo(rxManager)
    }



}
